package cn.fl.rebacc.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.rebacc.web.service.ISaleRebAccInfoService;
import cn.fl.rebacc.web.service.ISaleRebAccOrgRService;
import cn.fl.rebacc.web.vo.SaleRebAccInfoVO;
import cn.fl.rebacc.web.vo.SaleRebAccOrgRVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.SysFlowManageVQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.SysFlowManageVDTO;
import fl.spl.facade.framework.constant.DictionaryConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.FlowStartRelInfoCfgEnum;
import fl.spl.facade.rebacc.condition.SaleRebAccInfoQC;
import fl.spl.facade.rebacc.condition.SaleRebAccOrgRQC;
import fl.spl.facade.spl.constant.SplInfoConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 公用销售返利账号信息表 控制层
 */
@Controller
@RequestMapping("/rebacc/salerebaccinfo")
public class SaleRebAccInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SaleRebAccInfoController.class);

	/**
	 * SaleRebAccInfo 服务层BEAN
	 */
	@Autowired
	private ISaleRebAccInfoService saleRebAccInfoService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService ;
	
	@Autowired
	private IFlowApiService flowApiService  ;
	
	@Autowired
	private ISaleRebAccOrgRService saleRebAccOrgRService ;
	
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService ;
	
	@Autowired
	private ISysRegionApiService sysRegionApiService ;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("rebacc/saleRebAccInfoList");
		try{
			//获取审核状态集合
			List<KeyValueVO> searchAudStsCdList = this.getKvList(DictionaryConstant.CODE_AUD_STS_CD);
			//获取账号类型集合
			List<KeyValueVO> bizTypCdList = this.getKvList(DictionaryConstant.CODE_BIZ_TYP_CD);
			List<KeyValueVO> purpCdList = this.sysDictionaryApiService.getKvList(DictionaryConstant.SALE_ACC_PURP_CD,
					SplSystemConstant.SPL_SYS_CD,
					SplSystemConstant.DEFAULT_ORG_CD);
			view.addObject("searchAudStsCdList", searchAudStsCdList);
			//List<KeyValueVO> purpCdList = this.getKvList(DictionaryConstant.SALE_ACC_PURP_CD);
			view.addObject("purpCdList", purpCdList);
			view.addObject("bizTypCdList", bizTypCdList);
		}catch(BaseException ex){
			BaseLogUtils.info(logger, "toListPage", "查询数据字典失败,Exception."+ex.getMessage());
		}catch(Exception ex){
			BaseLogUtils.info(logger, "toListPage", "查询数据字典失败,Exception."+ex.getMessage());
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		String isButton = request.getParameter("isButton");
		ModelAndView view = new ModelAndView("rebacc/saleRebAccInfoAdd");
		//获取账号类型集合
		List<KeyValueVO> bizTypCdList = this.getKvList(DictionaryConstant.CODE_BIZ_TYP_CD);
		view.addObject("bizTypCdList", bizTypCdList);
		//List<KeyValueVO> purpCdList = this.getKvList(DictionaryConstant.SALE_ACC_PURP_CD);
		List<KeyValueVO> purpCdList = this.sysDictionaryApiService.getKvList(DictionaryConstant.SALE_ACC_PURP_CD,
				SplSystemConstant.SPL_SYS_CD,
				SplSystemConstant.DEFAULT_ORG_CD);
		view.addObject("purpCdList", purpCdList);
		view.addObject("id",id);
		view.addObject("isButton", isButton);
		if(StringUtils.isEmpty(id)){
			view.addObject("disabled",BaseConstant.IS_YESNO_NO);
		}else{
			view.addObject("disabled",BaseConstant.IS_YESNO_YES);
			
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("rebacc/saleRebAccInfo/saleRebAccInfoModify");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("rebacc/saleRebAccInfoDetail");
		String bizTypCd = "";
		if(StringUtils.isNotEmpty(id)){
			SaleRebAccInfoVO saleRebAccInfoVO = this.saleRebAccInfoService.selectById(Long.valueOf(id));
			bizTypCd = saleRebAccInfoVO.getBizTypCd();
		}
		view.addObject("bizTypCd", bizTypCd);
		view.addObject("id", id);
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String rcptUnt = request.getParameter("rcptUnt");//收款方
		String accNo = request.getParameter("accNo");//收款账号
		String bkNm = request.getParameter("bkNm");//开户行
		String audStsCd = request.getParameter("audStsCd");//审核状态
		String bizTypCd = request.getParameter("bizTypCd");//账号类型
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SaleRebAccInfoQC qc = new SaleRebAccInfoQC();
		if (StringUtils.isNotEmpty(rcptUnt)) {
			//TODO SOMTHING
			qc.setRcptUnt(rcptUnt);
		}
		if(StringUtils.isNotEmpty(accNo)){
			qc.setAccNo(accNo);
		}
		if(StringUtils.isNotEmpty(bkNm)){
			qc.setBkNm(bkNm);
		}
		if(StringUtils.isNotEmpty(audStsCd)){
			qc.setAudStsCd(audStsCd);
		}
		if(StringUtils.isNotEmpty(bizTypCd)){
			qc.setBizTypCd(bizTypCd);;
		}
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);

		//TODO SOMETHING
		BaseLogUtils.info(logger, "initList", "分页查询所有数据."+JSON.toJSONString(page));
		Pager pager = this.saleRebAccInfoService.searchListPage(page);
		List<SaleRebAccInfoVO> list = (List<SaleRebAccInfoVO>) pager.getResultList();
		if(CollectionUtils.isNotEmpty(list)){
			
			for (SaleRebAccInfoVO saleRebAccInfoVO : list) {
				if(StringUtils.isNotEmpty(saleRebAccInfoVO.getFromSource()) && saleRebAccInfoVO.getFromSource().equals(SplSystemConstant.FL_WEB_CHL_CD)){
					saleRebAccInfoVO.setFromSource("web端新增");
				}
			}
			
			//账号类型
			Map<String, String> bizTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CODE_BIZ_TYP_CD);
			if(CollectionUtils.isMapNotEmpty(bizTypCdMap)){
				for (SaleRebAccInfoVO saleRebAccInfoVO : list) {
					saleRebAccInfoVO.setBizTypCdNm(bizTypCdMap.get(saleRebAccInfoVO.getBizTypCd()));
				}
			}
			//账户用途
			Map<String, String> purpTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.PURP_CD);
			if(CollectionUtils.isMapNotEmpty(purpTypCdMap)){
				for (SaleRebAccInfoVO saleRebAccInfoVO : list) {
					saleRebAccInfoVO.setPurpCdNm(purpTypCdMap.get(saleRebAccInfoVO.getPurpCd()));
				}
			}
			Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CODE_AUD_STS_CD);
			if(CollectionUtils.isMapNotEmpty(audStsCdMap)){
				for (SaleRebAccInfoVO saleRebAccInfoVO : list) {
					saleRebAccInfoVO.setAudStsCdNm(audStsCdMap.get(saleRebAccInfoVO.getAudStsCd()));
				}
			}
		}
		ListPageVO<SaleRebAccInfoVO> listPage = new ListPageVO<SaleRebAccInfoVO>(list, pager.getTotalCount());
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		SaleRebAccInfoVO entity = null;
		try {
			entity = new SaleRebAccInfoVO();
			//TODO ADD PARAM
			this.getReauestParamByAdd(request, entity);
			BaseLogUtils.info(logger, "add", "新增数据,DATA."+JSON.toJSONString(entity));
			Long id = this.saleRebAccInfoService.add(entity);
			if(StringUtils.isNotEmpty(id) && id != 0){
				BaseLogUtils.info(logger, "add", "新增成功,id="+id,CurrentThreadContext.getCurrentUserName());
			}
			result.setData(id);
			this.uploadAttchment(request,result,id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增对象失败,name["+name+"].", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "add", "新增对象失败,name["+name+"].", CurrentThreadContext.getCurrentUserName(), ex);
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SaleRebAccInfoVO entity = null;
		try {
			entity = new SaleRebAccInfoVO();
			entity.setId(Long.valueOf(id));
			this.getReauestParamByModify(request, entity);
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.saleRebAccInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			result.setData(id);
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "modify", "修改对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.saleRebAccInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SaleRebAccInfoVO vo = this.saleRebAccInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			Map<String, String> bizTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CODE_BIZ_TYP_CD);
			if(CollectionUtils.isMapNotEmpty(bizTypCdMap)){
				vo.setBizTypCdNm(bizTypCdMap.get(vo.getBizTypCd()));
			}
			//账户用途
			//账户用途
			Map<String, String> purpTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.SPL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.SALE_ACC_PURP_CD);
			if(CollectionUtils.isMapNotEmpty(purpTypCdMap)){
				vo.setPurpCdNm(purpTypCdMap.get(vo.getPurpCd()));
			}
			Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CODE_AUD_STS_CD);
			if(CollectionUtils.isMapNotEmpty(audStsCdMap)){
					vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
			}
			//查询区域信息
	        String rgnPrCd = vo.getRgnPrCd();
	        String rgnCyCd = vo.getRgnCyCd();
	        StringBuffer rgnNms = new StringBuffer();
	        if (StringUtils.isNotBlank(rgnPrCd)) {
	            SysRegionDTO sysRegionDTO = this.sysRegionApiService.getRegionByRgnCd(rgnPrCd, SplSystemConstant.FL_SYS_CD);
	            if (null != sysRegionDTO) {
	                rgnNms.append(sysRegionDTO.getRgnNm());
	            }
	        }
	        if (StringUtils.isNotBlank(rgnCyCd)) {
	            SysRegionDTO sysRegionDTO = this.sysRegionApiService.getRegionByRgnCd(rgnCyCd, SplSystemConstant.FL_SYS_CD);
	            if (null != sysRegionDTO) {
	                rgnNms.append("-");
	                rgnNms.append(sysRegionDTO.getRgnNm());
	            }
	        }
	        vo.setRgnNms(rgnNms.toString());
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}
	
	/**
	 * 启用作废操作
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/modifyAccStsCd.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object modifyAccStsCd(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String btnTyp = request.getParameter("btnTyp");
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		
		if(StringUtils.isEmpty(id)){
			result.setInfo("主键ID不能为空");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result ;
		}
		try{
			SaleRebAccInfoVO vo = new SaleRebAccInfoVO();
			vo.setId(Long.valueOf(id));
			if(StringUtils.isNotEmpty(btnTyp) && "start".equals(btnTyp)){
				vo.setAccStsCd("VALID");
			}else{
				vo.setAccStsCd("VOID");
			}
			vo.setMdfTm(new Date());
			vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean modify = this.saleRebAccInfoService.modify(vo);
			if(!modify){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败");
			}
		}catch(BaseException ex){
			BaseLogUtils.info(logger, "modifyAccStsCd", "修改账号状态失败,ID="+id+",Exception."+ex.getMessage());
			result.setInfo(ex.getMessage());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
		}catch(Exception ex){
			BaseLogUtils.info(logger, "modifyAccStsCd", "修改账号状态失败,ID="+id+",Exception."+ex.getMessage());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误");
		}
		return result ;
	}
	
	/**
	 * 启用作废操作
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("操作失败");
			return result ;
		}
		try{
			SysFlowManageVQueryCondition condition = new SysFlowManageVQueryCondition();
			condition.setIsDel(BaseConstant.IS_YESNO_NO);
			condition.setIsValid(BaseConstant.IS_YESNO_YES);
			condition.setModelTyp(FlowStartRelInfoCfgEnum.FLOW_SALE_REB_ACC.getModelTyp());
			condition.setSysCd(SplSystemConstant.FL_SYS_CD);
			condition.setOrgCd(SplSystemConstant.DEFAULT_ORG_CD);
			List<SysFlowManageVDTO> list = this.flowApiService.searchFlowManageVListForStart(condition );
			if(CollectionUtils.isEmpty(list)){
				result.setInfo("发起流程失败，未找到符合条件的流程，请重试！");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				return result ;
			}
			SysFlowManageVDTO sysFlowManageVDTO = list.get(0);
			BaseLogUtils.info(logger, "addFlowStart", "sysFlowManageVDTO："+JSON.toJSONString(sysFlowManageVDTO));
			FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
			//流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);

			flowStartParamsDTO.setWordsInTheTable(FlowStartRelInfoCfgEnum.FLOW_SALE_REB_ACC.getWordsInTheTable());
			//流程定义标识(必填)
			flowStartParamsDTO.setProcDefKey(sysFlowManageVDTO.getProcDefKey());
			//流程定义ID(必填)
			flowStartParamsDTO.setProcDefId(sysFlowManageVDTO.getProcDefId());
			//流程定义名称(自定义)
			flowStartParamsDTO.setProcNo(sysFlowManageVDTO.getProcNo());

			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//业务数据主键(必填)
			flowStartParamsDTO.setBusinessKey(id);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
			//业务类型(必填)-用于区分操作表标识
			flowStartParamsDTO.setBusinessType(FlowStartRelInfoCfgEnum.FLOW_SALE_REB_ACC.getBusinessType());//确认用不用
			//模块类型(流程业务分类): 针对直接启动流程的业务使用
			flowStartParamsDTO.setModelTyp(FlowStartRelInfoCfgEnum.FLOW_SALE_REB_ACC.getModelTyp());//需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm()+"、供应商流程大字段参数未定!");
			BaseLogUtils.info(logger, "addFlowStart", "发起审核流程,flowStartParamsDTO:"+JSON.toJSONString(flowStartParamsDTO));
			DataResultDTO dataResultDTO =  this.saleRebAccInfoService.addSplAdmissionFlowStart(flowStartParamsDTO);
			if(dataResultDTO != null){
				if(dataResultDTO.getCode() != null && !dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
				}
			}

		}catch(BaseException ex){
			result.setInfo(ex.getMessage());
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			BaseLogUtils.info(logger, "addFlowStart", "发起流程失败,id="+id+",Exception."+ex.getMessage());
		}catch(Exception ex){
			result.setInfo("系统错误");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			BaseLogUtils.info(logger, "addFlowStart", "发起流程失败,id="+id+",Exception."+ex.getMessage());
			
		}
		return result ;
	}
	
	private void getReauestParamByAdd(HttpServletRequest request, SaleRebAccInfoVO saleRebVO) throws BaseException{
		this.getReauestParam(request, saleRebVO);
		saleRebVO.setCrtTm(new Date());
		saleRebVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		saleRebVO.setFromSource(SplSystemConstant.FL_WEB_CHL_CD);
		saleRebVO.setAccStsCd("VALID");
		saleRebVO.setIsValid(BaseConstant.IS_YESNO_YES);
		saleRebVO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_NON);
	}
	private void getReauestParamByModify(HttpServletRequest request, SaleRebAccInfoVO saleRebVO) throws BaseException{
		this.getReauestParam(request, saleRebVO);
		saleRebVO.setMdfTm(new Date());
		saleRebVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
	}
	private void getReauestParam(HttpServletRequest request, SaleRebAccInfoVO saleRebVO) throws BaseException{
		String id = request.getParameter("id");
		String rcptUnt = request.getParameter("rcptUnt");
		String accNo = request.getParameter("accNo");
		String bkNm = request.getParameter("bkNm");
		String bkNo = request.getParameter("bkNo");
		String rgnPrCd = request.getParameter("rgnPrCd");
		String rgnCyCd = request.getParameter("rgnCyCd");
		String bizTypCd = request.getParameter("bizTypCd");
		String purpCd = request.getParameter("purpCd");
		String contTel = request.getParameter("contTel");
		String bkRem = request.getParameter("bkRem");
		String fileParams = request.getParameter("fileParams");//附件上传信息		
		
		String attchmnt = request.getParameter("docArray");

		String disable = request.getParameter("disable");
		String certNo = request.getParameter("certNo");//收款人身份证号
		String bkResTel = request.getParameter("bkResTel");//银行预留手机号
		
		if(StringUtils.isEmpty(id) && "0".equals(bizTypCd)){
			if(StringUtils.isEmpty(attchmnt)){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"请上传附件信息");
			}
		}
		
		if(StringUtils.isEmpty(rcptUnt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"收款方不能为空");
		}
		if(StringUtils.isEmpty(accNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"收款账号不能为空");
		}
		//添加排重
				SaleRebAccInfoQC condition = new SaleRebAccInfoQC();
				//condition.setRcptUnt(rcptUnt);
				condition.setAccNo(accNo);
				condition.setIsDel(BaseConstant.IS_YESNO_NO);
				condition.setIsValid(BaseConstant.IS_YESNO_YES);
				List<SaleRebAccInfoVO> list = this.saleRebAccInfoService.searchList(condition );
				
				if(StringUtils.isNotEmpty(id)){
					Long saleId = Long.valueOf(id);
					if(CollectionUtils.isNotEmpty(list)){
						if(list.size() > 1){
							this.addSaleRebAccOrgR(list.get(0));
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604,"账号信息已存在,该账户将自动添加到当前事业部下");
						}else{
							SaleRebAccInfoVO saleRebAccInfoVO = list.get(0);
							if(!saleId.equals(saleRebAccInfoVO.getId())){
								this.addSaleRebAccOrgR(list.get(0));
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604,"账号信息已存在,该账户将自动添加到当前事业部下");
							}
						}
					}
					
				}else{
					if(CollectionUtils.isNotEmpty(list)){
						this.addSaleRebAccOrgR(list.get(0));
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604,"账号信息已存在,该账户将自动添加到当前事业部下");
					}
				}
		if(StringUtils.isEmpty(bkNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"开户行不能为空");
		}
		if(StringUtils.isEmpty(bkNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"开户行行号不能为空");
		}
		if(StringUtils.isEmpty(rgnPrCd) || StringUtils.isEmpty(rgnCyCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"区域不能为空");
		}
		if(StringUtils.isEmpty(bizTypCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"账号不能为空");
		}else{
			if(BaseConstant.IS_YESNO_YES_STR.equals(bizTypCd) && StringUtils.isEmpty(disable)){
				if (StringUtils.isBlank(certNo) || !StringUtils.isIdCardNumber(certNo)) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "收款方身份证号不能为空,并且是正确的身份证号格式!");
				}
				if (StringUtils.isBlank(bkResTel) || !StringUtils.checkMobileNumber(bkResTel)) {
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "银行预留手机号不能为空,并且是正确的手机号格式!");
				}
			}
		}
		if(StringUtils.isEmpty(purpCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"账号用途不能为空");
		}
		//附件信息
		//解析附件上传信息
		List<SysUlFilesRecVO> sysUlFilesRecVOList = new ArrayList<SysUlFilesRecVO>();
		if(StringUtils.isNotEmpty(fileParams)){
			List<Map<String, String>> fileParamsList = new ArrayList<Map<String, String>>(); 
			JSONArray arry = JSONArray.fromObject(fileParams);
			for (int i = 0; i < arry.size(); i++) {
				net.sf.json.JSONObject jsonObject = arry.getJSONObject(i);
				Iterator<?> it = jsonObject.keys();  
				HashMap<String, String> hMap = new HashMap<String, String>();
				while (it.hasNext())  
				{  
					String key = String.valueOf(it.next());  
					String value = (String) jsonObject.get(key);  
					hMap.put(key, value);  
				} 
				fileParamsList.add(hMap);
			}
			for (Map<String, String> map : fileParamsList) {
				SysUlFilesRecVO sysUlFilesRecVO = new SysUlFilesRecVO();
				sysUlFilesRecVO.setFileNm(map.get("fileNm"));
				sysUlFilesRecVO.setFilePath(map.get("filePath"));
				sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+map.get("filePath"));
				sysUlFilesRecVO.setCrtTm(new Date());
				sysUlFilesRecVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				//TODO 这里应该先读配置  按配置保存   这里先写死后期再改---------------Start
				sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
				sysUlFilesRecVO.setOrgCd("0000");
				sysUlFilesRecVO.setCfgCd(SplInfoConstant.SPL_BANK_FILE_UPLOAD_CFG_CD);
				sysUlFilesRecVO.setCfgDtlCd(SplInfoConstant.SPL_BANK_FILE_UPLOAD_CFG_DTL_CD);
				//TODO---------------------------------------------------------End
				//默认验证状态:未验证
				sysUlFilesRecVO.setAudStsCd(PropertiesCacheUtils.getProperty(fl.constant.facade.framework.constant.DictionaryConstant.CODE_GRP_VALID_STATUS_CD_A));
				sysUlFilesRecVOList.add(sysUlFilesRecVO);
			}
		}
		if(saleRebVO == null){
			saleRebVO = new SaleRebAccInfoVO();
		}
		saleRebVO.setRcptUnt(rcptUnt);
		saleRebVO.setAccNo(accNo);
		saleRebVO.setBkNm(bkNm);
		saleRebVO.setBkNo(bkNo);
		saleRebVO.setRgnCyCd(rgnCyCd);
		saleRebVO.setRgnPrCd(rgnPrCd);
		saleRebVO.setBizTypCd(bizTypCd);
		saleRebVO.setContTel(contTel);
		saleRebVO.setBkRem(bkRem);
		saleRebVO.setPurpCd(purpCd);

		saleRebVO.setCertNo(certNo);
		saleRebVO.setBkResTel(bkResTel);
	}
	
	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	private List<KeyValueVO> getKvList(String grpCd){
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "getKvList", "获取字典项组"+grpCd+"失败.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组"+grpCd+"失败,系统错误.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}
	
	private void addSaleRebAccOrgR(SaleRebAccInfoVO vo){
		boolean flag = true ;
		SaleRebAccOrgRQC saleRebAccOrgRQC = new SaleRebAccOrgRQC();
		saleRebAccOrgRQC.setAccId(vo.getId());
		//saleRebAccOrgRQC.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		List<SaleRebAccOrgRVO> rebaccOrgRList = this.saleRebAccOrgRService.searchList(saleRebAccOrgRQC );
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		if(StringUtils.isNotEmpty(orgCd) && orgCd.length() > 16){
			orgCd = orgCd.substring(0, 16);
		}
		String orgCd2 ;
		for (SaleRebAccOrgRVO saleRebAccOrgRVO : rebaccOrgRList) {
			if(StringUtils.isNotEmpty(saleRebAccOrgRVO.getOrgCd())){
				orgCd2 = saleRebAccOrgRVO.getOrgCd();
				if(orgCd2.length()>16){
					orgCd2 = orgCd2.substring(0, 16);
				}
				if(orgCd2.equals(orgCd)){
					flag = false ;
				}
			}
		}
		if(flag){
			SaleRebAccOrgRVO entity = new SaleRebAccOrgRVO();
			entity.setAccId(vo.getId());
			entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setIsValid(BaseConstant.IS_YESNO_YES);
			entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			BaseLogUtils.info(logger, "addSaleRebAccOrgR", "添加账户与组织架构关系，entity:"+JSON.toJSONString(entity));
			Long add = this.saleRebAccOrgRService.add(entity );
			if(StringUtils.isNotEmpty(add)){
				BaseLogUtils.info(logger, "addSaleRebAccOrgR", "添加账户与组织架构关系成功，id:"+add);
			}else{
				BaseLogUtils.info(logger, "addSaleRebAccOrgR", "添加账户与组织架构关系失败");
			}
		}
	}
	
	private void uploadAttchment(HttpServletRequest request, DataResultVO result, Long id) {
		String attchmnt = request.getParameter("docArray");
		if(StringUtils.isNotEmpty(attchmnt)){
			//上传解析
			try{
				String cfgCd = SplInfoConstant.SALE_REB_ACC_CFG_CD;
				String cfgDtlCd = SplInfoConstant.SALE_REB_ACC_UPLOAD_CFG_DTL_CD;
				String tabNm = "SALE_REB_ACC_INFO";
				String cfgOrgCd = SplSystemConstant.DEFAULT_ORG_CD;
				Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, "客户主要信息附件!", null, null, false, cfgOrgCd);
				if(null == attchmntPass || attchmntPass == false){
					result.setInfo(result.getInfo()+"-附件上传失败!");
				}
			}catch(Exception e){
				BaseLogUtils.error(logger, "uploadAttchment", result.getInfo()+"-附件上传失败!", e);
				result.setInfo(result.getInfo()+"-附件上传失败!");
			}
		}
	}
}

